package com.wondersgroup.tjfx.bo.impl.form;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.mongodb.util.JSON;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.quick.framework.boot.repository.nosql.mongodb.inter.IMongoOperator;
import com.wondersgroup.tjfx.bo.inter.form.IForm;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

@Service("formImpl")
public class FormImpl implements IForm {

    @Autowired
    IMongoOperator mongoOperator;

    /**
     * 查询模板列表
     *
     * @return
     */
    @Override
    public String queryForm(String formMetadata, String type) {
        String str = "";
        try {
            /* momgo模糊匹配使用java的正则表达式 */
            Pattern p = Pattern.compile("^.*" + formMetadata + ".*$", Pattern.CASE_INSENSITIVE);
            JSONArray ary = (JSONArray) mongoOperator.executeQuery(type, QueryBuilder.start("formMetadata").regex(p), new String[]{"formMetadata","isLinkResource"});
            str = ary.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    @Override
    public String queryFormXx(String type) {
        String str = "";
        try {
            JSONArray ary = (JSONArray) mongoOperator.executeQuery(type, QueryBuilder.start());
            str = ary.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 获取模板配置
     *
     * @return
     */
    @Override
    public String receiveForm(String tableName, String id) {
        String str = "";
        JSONObject result = new JSONObject();
        try {
            JSONArray ary = (JSONArray) mongoOperator.executeQuery(tableName, QueryBuilder.start("_id").is(new ObjectId(id)));
            if (ary.size() > 0) {
                result = ary.getJSONObject(0);
                return result.toString();
            } else {
                return result.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 保存
     *
     * @return
     */
    @Override
    public String saveForm(String formID, String jsonStr, String type) {
        ResultObject ro = new ResultObject();
        try {
            if (StringUtils.isEmpty(formID)) {
                formID = addForm(jsonStr, type);
                ro.setInfo(type, formID);
            } else {
                updateForm(type, jsonStr, formID);
            }
        } catch (Exception e) {
            ro.changeFaultState("保存失败");
            e.printStackTrace();
        }

        return ro.toJsonStr();
    }

    @Override
    public String deleteForm(String formId, String type) {
        ResultObject ro = new ResultObject();
        try {
            if (isReferForm(formId)) {
                mongoOperator.executeDeleteOne(type, QueryBuilder.start("_id").is(new ObjectId(formId)));
            } else {
                ro.changeFaultState("选择器被引用");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ro.changeFaultState(e.getLocalizedMessage());
        }
        return ro.toJsonStr();
    }

    private boolean isReferForm(String formId) {
        boolean flag = false;
        try {
            JSONArray jArrayZtst = (JSONArray) mongoOperator.executeQuery("zbst", QueryBuilder.start("conditionId").is(formId));
            JSONArray jArrayMbpz = (JSONArray) mongoOperator.executeQuery("mbpz", QueryBuilder.start("conditionId").is(formId));
            flag = jArrayZtst.isEmpty() && jArrayMbpz.isEmpty();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    private String addForm(String json, String type) {
        try {
            DBObject dbo = (DBObject) JSON.parse(json);
            String BDID = mongoOperator.executeInsertOneAsFile(type, dbo);
            return BDID;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void updateForm(String type, String jsonStr, String formId) {
        try {
            DBObject dbo = (DBObject) JSON.parse(jsonStr);
            mongoOperator.executeUpdate(type, QueryBuilder.start("_id").is(new ObjectId(formId)), dbo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据类型获取resource_iframe表的数据
     *
     * @param type
     * @return
     */
    @Override
    public String receiveIframe(String type) {

        String str = "";
        JSONObject result = new JSONObject();
        try {
            JSONArray ary = (JSONArray) mongoOperator.executeQuery("resource_iframe", QueryBuilder.start("type").is(type));
            if (ary.size() > 0) {
                result = ary.getJSONObject(0);
                return result.toString();
            } else {
                return result.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    @Override
    public String receiveForm(String tableName) {
        JSONArray result = new JSONArray();
        try {
            result = (JSONArray) mongoOperator.executeQuery(tableName, null, new String[]{"_id"});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toJSONString();
    }

    @Override
    public String queryZbst(String type) {
        JSONArray result = new JSONArray();
        try {
            result = (JSONArray) mongoOperator.executeQuery("zbst", QueryBuilder.start("ZBDL").is(type), new String[]{"formMetadata", "ZBID"});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toJSONString();
    }

    @Override
    public String queryLinked(String type, String name,String isLink) {
        JSONArray ary = new JSONArray();
        try {
            Pattern p = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            QueryBuilder query = QueryBuilder.start("formMetadata").regex(p);
            if(!StringUtils.isEmpty(type)){
                query = query.and("isLinkResource").is(isLink);
            }
            ary = mongoOperator.executeQuery(type, query, new String[]{"BDID", "formMetadata"});
            int len = ary.size();
            for (int i = 0; i < len; i++) {
                JSONObject json = ary.getJSONObject(i);
                String formMetadata = json.getString("formMetadata");
                JSONObject form = com.alibaba.fastjson.JSON.parseObject(formMetadata);
                String mbmc = form.getString("MBMC");
                json.put("MBMC", mbmc);
                json.remove("formMetadata");
                String bdid = json.getJSONObject("_id").getString("$oid");
                json.put("BDID", bdid);
                json.remove("_id");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ary.toJSONString();
    }

}
